import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class PolygonGUI extends JFrame {
    private final List<Shape> shapes = new ArrayList<>();
    private Shape currentShape;
    private JTextField parameter1Field;
    private JTextField parameter2Field;
    private JComboBox<String> shapeComboBox;
    private DrawingPanel drawingPanel;
    private JTextArea infoTextArea;

    public PolygonGUI() {
        initializeUI();
    }

    private void initializeUI() {
        setTitle("多边形绘制工具 - 图形计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(10, 10));

        // 创建输入面板
        JPanel inputPanel = createInputPanel();
        add(inputPanel, BorderLayout.NORTH);

        // 创建绘图和信息面板
        JSplitPane centerSplitPane = createCenterPanel();
        add(centerSplitPane, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setSize(800, 600);
        setLocationRelativeTo(null);
    }

    private JPanel createInputPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createTitledBorder("图形参数输入"));

        // 图形类型选择
        panel.add(new JLabel("图形类型:"));
        String[] shapes = {"长方形", "圆形", "三角形", "平行四边形", "梯形", "菱形",
                "正多边形", "椭圆", "扇形", "圆环", "10边星形"};
        shapeComboBox = new JComboBox<>(shapes);
        panel.add(shapeComboBox);

        // 参数1输入
        panel.add(new JLabel("长:"));
        parameter1Field = new JTextField(8);
        panel.add(parameter1Field);

        // 参数2输入
        panel.add(new JLabel("宽:"));
        parameter2Field = new JTextField(8);
        panel.add(parameter2Field);

        // 动态更新参数标签
        shapeComboBox.addActionListener(e -> updateParameterLabels());
        updateParameterLabels();

        return panel;
    }

    private JSplitPane createCenterPanel() {
        // 绘图面板
        drawingPanel = new DrawingPanel();

        // 信息显示区域
        infoTextArea = new JTextArea(10, 30);
        infoTextArea.setEditable(false);
        infoTextArea.setBorder(BorderFactory.createTitledBorder("图形信息"));
        JScrollPane scrollPane = new JScrollPane(infoTextArea);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, drawingPanel, scrollPane);
        splitPane.setResizeWeight(0.6);

        return splitPane;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout());

        JButton calculateButton = new JButton("计算并绘制");
        calculateButton.addActionListener(new CalculateListener());

        JButton viewAllButton = new JButton("查看所有图形");
        viewAllButton.addActionListener(e -> showAllShapes());

        JButton statsButton = new JButton("统计信息");
        statsButton.addActionListener(e -> showStatistics());

        JButton clearButton = new JButton("清空图形");
        clearButton.addActionListener(e -> clearShapes());

        panel.add(calculateButton);
        panel.add(viewAllButton);
        panel.add(statsButton);
        panel.add(clearButton);

        return panel;
    }

    private void updateParameterLabels() {
        String selectedShape = (String) shapeComboBox.getSelectedItem();
        if (selectedShape == null) return;

        switch (selectedShape) {
            case "长方形":
                setParameterLabels("长", "宽");
                break;
            case "圆形":
                setParameterLabels("半径", "未使用");
                parameter2Field.setEnabled(false);
                break;
            case "三角形":
                setParameterLabels("底边", "高");
                break;
            case "正多边形":
                setParameterLabels("边长", "边数");
                break;
            case "椭圆":
                setParameterLabels("长轴", "短轴");
                break;
            case "扇形":
                setParameterLabels("半径", "角度");
                break;
            case "圆环":
                setParameterLabels("内半径", "外半径");
                break;
            case "菱形":
                setParameterLabels("边长", "角度"); // 或者 "对角线1", "对角线2"
                break;
            case "平行四边形":
                setParameterLabels("底边", "高");
                break;
            case "梯形":
                setParameterLabels("上底", "下底");
                break;
            default:
                setParameterLabels("参数1", "参数2");
        }
        if (!selectedShape.equals("圆形")) {
            parameter2Field.setEnabled(true);
        }
    }

    private void setParameterLabels(String label1, String label2) {
        // 修复：移除冗余的类型转换
        Container parent = parameter1Field.getParent();
        if (parent != null) {
            Component[] components = parent.getComponents();
            for (Component comp : components) {
                if (comp instanceof JLabel) {
                    JLabel label = (JLabel) comp;
                    String text = label.getText();
                    if (text != null) {
                        if (text.startsWith("长") || text.startsWith("半径") || text.startsWith("底边") ||
                                text.startsWith("边长") || text.startsWith("长轴") || text.startsWith("对角线1") ||
                                text.startsWith("上底") || text.startsWith("参数1")) {
                            label.setText(label1 + ":");
                        } else if (text.startsWith("宽") || text.startsWith("高") || text.startsWith("边数") ||
                                text.startsWith("短轴") || text.startsWith("角度") || text.startsWith("外半径") ||
                                text.startsWith("对角线2") || text.startsWith("下底") || text.startsWith("参数2")) {
                            label.setText(label2 + ":");
                        }
                    }
                }
            }
        }
    }

    // 绘图面板内部类
    private class DrawingPanel extends JPanel {
        public DrawingPanel() {
            setPreferredSize(new Dimension(400, 400));
            setBackground(Color.WHITE);
            setBorder(BorderFactory.createTitledBorder("图形预览"));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            if (currentShape != null) {
                drawCurrentShape(g);
            } else if (!shapes.isEmpty()) {
                drawAllShapes(g);
            } else {
                // 显示提示信息
                g.setColor(Color.GRAY);
                g.drawString("请输入参数并点击计算", getWidth()/2 - 60, getHeight()/2);
            }
        }

        private void drawCurrentShape(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int centerX = getWidth() / 2;
            int centerY = getHeight() / 2;
            int size = Math.min(getWidth(), getHeight()) / 4; // 动态大小

            g2d.setColor(Color.BLUE);
            g2d.setStroke(new BasicStroke(2));

            // 根据图形类型绘制
            String shapeType = currentShape.getName();
            if (shapeType.contains("长方")) {
                drawRectangle(g2d, centerX - size, centerY - size/2, size * 2, size);
            } else if (shapeType.contains("圆") && !shapeType.contains("环")) {
                drawCircle(g2d, centerX, centerY, size);
            } else if (shapeType.contains("三角")) {
                drawTriangle(g2d, centerX, centerY, size);
            } else if (shapeType.contains("正") && shapeType.contains("边")) {
                drawRegularPolygon(g2d, centerX, centerY, size, extractSideCount(shapeType));
            } else if (shapeType.contains("椭圆")) {
                drawEllipse(g2d, centerX, centerY, size, size * 2/3);
            } else if (shapeType.contains("菱形")) {
                drawRhombus(g2d, centerX, centerY, size);
            } else if (shapeType.contains("圆环")) {
                drawAnnulus(g2d, centerX, centerY, size * 2/3, size);
            } else {
                // 默认绘制矩形
                drawRectangle(g2d, centerX - size/2, centerY - size/2, size, size);
            }
        }

        private void drawAllShapes(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int shapeSize = Math.min(getWidth(), getHeight()) / 4;
            int cols = 3;
            int index = 0;

            for (Shape shape : shapes) {
                int row = index / cols;
                int col = index % cols;
                int x = col * shapeSize + 20;
                int y = row * shapeSize + 20;

                g2d.setColor(new Color(100 + index * 30, 150, 200));
                g2d.setStroke(new BasicStroke(1));

                // 简化的图形绘制
                g2d.drawRect(x, y, shapeSize - 10, shapeSize - 10);
                g2d.setColor(Color.BLACK);
                String shapeName = shape.getName();
                g2d.drawString(shapeName.length() > 4 ? shapeName.substring(0, 4) : shapeName, x + 5, y + 15);

                index++;
                if (index >= 9) break; // 最多显示9个
            }
        }

        private void drawRectangle(Graphics2D g2d, int x, int y, int width, int height) {
            g2d.drawRect(x, y, width, height);
        }

        private void drawCircle(Graphics2D g2d, int centerX, int centerY, int radius) {
            g2d.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
        }

        private void drawTriangle(Graphics2D g2d, int centerX, int centerY, int baseSize) {
            int height = (int) (baseSize * 0.866);
            int[] xPoints = {centerX, centerX - baseSize/2, centerX + baseSize/2};
            int[] yPoints = {centerY - height/2, centerY + height/2, centerY + height/2};
            g2d.drawPolygon(xPoints, yPoints, 3);
        }

        private void drawEllipse(Graphics2D g2d, int centerX, int centerY, int width, int height) {
            g2d.drawOval(centerX - width/2, centerY - height/2, width, height);
        }

        private void drawRhombus(Graphics2D g2d, int centerX, int centerY, int size) {
            int[] xPoints = {centerX, centerX + size/2, centerX, centerX - size/2};
            int[] yPoints = {centerY - size/2, centerY, centerY + size/2, centerY};
            g2d.drawPolygon(xPoints, yPoints, 4);
        }

        private void drawAnnulus(Graphics2D g2d, int centerX, int centerY, int innerRadius, int outerRadius) {
            g2d.drawOval(centerX - outerRadius, centerY - outerRadius, outerRadius * 2, outerRadius * 2);
            g2d.drawOval(centerX - innerRadius, centerY - innerRadius, innerRadius * 2, innerRadius * 2);
        }

        private void drawRegularPolygon(Graphics2D g2d, int centerX, int centerY, int radius, int sides) {
            Polygon polygon = new Polygon();
            for (int i = 0; i < sides; i++) {
                double angle = 2 * Math.PI * i / sides - Math.PI / 2;
                int px = centerX + (int) (radius * Math.cos(angle));
                int py = centerY + (int) (radius * Math.sin(angle));
                polygon.addPoint(px, py);
            }
            g2d.drawPolygon(polygon);
        }

        private int extractSideCount(String shapeName) {
            if (shapeName.contains("三")) return 3;
            if (shapeName.contains("四")) return 4;
            if (shapeName.contains("五")) return 5;
            if (shapeName.contains("六")) return 6;
            if (shapeName.contains("八")) return 8;
            if (shapeName.contains("十")) return 10;
            return 6;
        }
    }

    // 计算监听器内部类
    private class CalculateListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                String shapeType = (String) shapeComboBox.getSelectedItem();
                if (shapeType == null) {
                    JOptionPane.showMessageDialog(PolygonGUI.this,
                            "请选择图形类型！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double param1 = Double.parseDouble(parameter1Field.getText().trim());
                double param2 = 0;

                if (parameter2Field.isEnabled() && !parameter2Field.getText().trim().isEmpty()) {
                    param2 = Double.parseDouble(parameter2Field.getText().trim());
                }

                // 创建图形对象
                currentShape = createShape(shapeType, param1, param2);
                if (currentShape != null) {
                    shapes.add(currentShape);

                    // 更新信息显示
                    updateInfoDisplay();

                    // 重绘画布
                    drawingPanel.repaint();

                    // 显示成功消息
                    JOptionPane.showMessageDialog(PolygonGUI.this,
                            "📌 图形添加成功！\n" + currentShape.getInfo(),
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                }

            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(PolygonGUI.this,
                        "请输入有效的数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
            } catch (IllegalArgumentException ex) {
                JOptionPane.showMessageDialog(PolygonGUI.this,
                        ex.getMessage(), "参数错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(PolygonGUI.this,
                        "创建图形时发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }

        private Shape createShape(String type, double param1, double param2) {
            try {
                switch (type) {
                    case "长方形":
                        return new Rectangle(param1, param2);
                    case "圆形":
                        return new Circle(param1);
                    case "三角形":
                        // 根据你的Triangle类构造函数调整
                        // 如果只需要底和高：return new Triangle(param1, param2);
                        return new Triangle(param1, param2, Math.sqrt(param1*param1 + param2*param2));
                    case "正多边形":
                        return new RegularPolygon(param1, (int)param2);
                    case "菱形":
                        // 修复：根据你的Rhombus类构造函数调整
                        // 如果只需要边长：return new Rhombus(param1);
                        // 如果需要两个对角线：return new Rhombus(param1, param2);
                        // 如果需要边长和角度：return new Rhombus(param1, param2);
                        return new Rhombus(param1); // 暂时使用单参数构造函数
                    case "平行四边形":
                        return new Parallelogram(param1, param2);
                    case "梯形":
                        return new Trapezoid(param1, param2, Math.min(param1, param2));
                    case "椭圆":
                        return new Ellipse(param1, param2);
                    case "扇形":
                        return new Sector(param1, param2);
                    case "圆环":
                        return new Annulus(param1, param2);
                    case "10边星形":
                        return new DecagonStar(param1);
                    default:
                        throw new IllegalArgumentException("不支持的图形类型: " + type);
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("创建" + type + "失败: " + e.getMessage());
            }
        }
    }

    private void updateInfoDisplay() {
        StringBuilder sb = new StringBuilder();
        sb.append("==== 当前图形信息 ====\n");
        sb.append(currentShape.getInfo()).append("\n\n");

        sb.append("==== 所有已添加图形 ====\n");
        if (shapes.isEmpty()) {
            sb.append("暂无图形\n");
        } else {
            for (int i = 0; i < shapes.size(); i++) {
                sb.append(i + 1).append(" | ").append(shapes.get(i).getInfo()).append("\n");
            }
        }

        infoTextArea.setText(sb.toString());
    }

    private void showAllShapes() {
        if (shapes.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无图形数据", "信息", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        StringBuilder sb = new StringBuilder("==== 所有已添加图形 ====\n");
        sb.append("序号 | 图形详情\n");
        sb.append("--- | ---\n");
        for (int i = 0; i < shapes.size(); i++) {
            sb.append(i + 1).append(" | ").append(shapes.get(i).getInfo()).append("\n");
        }

        infoTextArea.setText(sb.toString());
        currentShape = null;
        drawingPanel.repaint();
    }

    private void showStatistics() {
        if (shapes.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无图形数据", "信息", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        double totalArea = 0;
        double totalPerimeter = 0;

        for (Shape shape : shapes) {
            totalArea += shape.calculateArea();
            totalPerimeter += shape.calculatePerimeter();
        }

        String stats = String.format(
                "==== 统计信息 ====\n" +
                        "图形总数: %d\n" +
                        "总面积: %.2f\n" +
                        "总周长: %.2f\n" +
                        "平均面积: %.2f\n" +
                        "平均周长: %.2f",
                shapes.size(), totalArea, totalPerimeter,
                totalArea / shapes.size(), totalPerimeter / shapes.size()
        );

        infoTextArea.setText(stats);
    }

    private void clearShapes() {
        int result = JOptionPane.showConfirmDialog(this,
                "确定要清空所有图形吗？", "确认清空", JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            shapes.clear();
            currentShape = null;
            infoTextArea.setText("图形数据已清空");
            drawingPanel.repaint();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PolygonGUI().setVisible(true));
    }
}